<template>
    <view class="page" :style="{ '--color': color }">
        <status-bar title="新增预约"></status-bar>
        <block v-for="(item, index) in pageData.data" :key="index">
            <view class="goods_item bgwhite m-bot24 p-re" v-for="(subItem, subIndex) in item.list" :key="subIndex">
                <view class="d-flex">
                    <image class="img" :src="$imgUrls(subItem.img)" mode="aspectFit"></image>
                    <view class="flex-1 d-flex f-column j-sb p-left20">
                        <view class="size28 color_33 bold ellipsis_2">{{ subItem.name }}</view>
                        <view class="thmeColor bold">
                            <text class="h6">￥</text>
                            <text class="size34">{{ subItem.price }}</text>
                        </view>
                    </view>
                </view>
                <view class="btn flexac p-ab" @click="opendetails(subItem)">
                    <text class="h6 color_33">查看详情</text>
                    <text class="iconfont icon-xiangyouxiayiye h6 color_99"></text>
                </view>
            </view>
        </block>
        <view class="bgwhite padding30 m-bot24">
            <view class="d-flex a-center m-bot30">
                <view class="divider"></view>
                <view class="size32 color_33 bold">预约时间</view>
                <view class="size28 color_B3">（必填）</view>
            </view>
            <view class="p-re m-bot30">
                <scroll-view class="scroll-row" scroll-x :scroll-into-view="'view' + scanDate" scroll-with-animation>
                    <view
                        :id="'view' + item.scanData"
                        class="date m-right10"
                        :class="{ thmeBg: scanDate == item.scanData, selected: select_date == item.scanData, 'm-right80': index == dateList.length - 1 }"
                        @click="selectDate(item, index)"
                        v-for="(item, index) in dateList"
                        :key="index"
                    >
                        <view class="size28" :class="scanDate == item.scanData ? 'white' : 'color_33'">{{ item.w }}</view>
                        <view class="h6" :class="scanDate == item.scanData ? 'white' : 'color_99'">{{ item.title }}</view>
                    </view>
                </scroll-view>
                <view class="calendar bgwhite p-ab" @click="showCalendar = true">
                    <text class="iconfont icon-qiandao size36 color_99"></text>
                    <view class="h6 color_99">选择</view>
                </view>
            </view>
            <swiper class="swiper" :current="current" @change="changeSwiper">
                <swiper-item v-for="(item, index) in dateList" :key="index">
                    <scroll-view class="scroll-row" scroll-x>
                        <view
                            class="time"
                            :class="{ disabled: subItem.num < 1, active: subscribe_date == subItem.subscribe_date }"
                            v-for="(subItem, subIndex) in item.timeLabel"
                            :key="subIndex"
                            @click="selectTime(subItem, item.scanData)"
                        >
                            <view class="top flexac f-column">
                                <view class="size28">{{ subItem.title }}</view>
                                <view class="size26">{{ subItem.times }}</view>
                            </view>
                            <view class="bottom flexac size22" :class="subItem.num < 1 ? 'color_B3' : 'color_99'">剩余 {{ subItem.num }}</view>
                        </view>
                    </scroll-view>
                </swiper-item>
            </swiper>
        </view>
        <view class="bgwhite padding30 m-bot24">
            <view class="d-flex a-center m-bot30">
                <view class="divider"></view>
                <view class="size32 color_33 bold">预约人信息</view>
            </view>
            <view class="d-flex a-center p-bot24 bot_bor_ee">
                <view class="label size28 color_33">姓名</view>
                <input class="flex-1 size28" v-model="uname" placeholder="请输入联系人姓名（必填）" />
            </view>
            <view class="d-flex a-center p-top24 p-bot24 bot_bor_ee">
                <view class="label size28 color_33">手机号码</view>
                <input class="flex-1 size28" v-model="utel" placeholder="请输入手机号码（必填）" />
            </view>
            <view class="d-flex a-center p-top24 p-bot24 bot_bor_ee" @click="showArrivalTime = true" v-if="arrivalTimeList.length">
                <view class="label size28 color_33">预计到达时间</view>
                <view class="flex-1 size28" :class="{ color_80: !arrivalTime }">{{ arrivalTime || '请选择' }}</view>
            </view>
            <view class="d-flex a-center p-top24">
                <view class="label size28 color_33">留言备注</view>
                <input class="flex-1 size28" v-model="remark" placeholder="选填" />
            </view>
        </view>
        <view class="bgwhite padding10-30 m-bot24">
            <Coupon :Sale="Sale" :pageData="requestData" @Use_couponId="Use_couponId"></Coupon>
            <Points :Sale="Sale" :pageData="requestData" @Use_points="Use_points"></Points>
        </view>
        <!-- 支付方式 -->
        <view class="payList" v-if="payMode.length">
            <view class="d-flex a-center p-left30">
                <view class="divider"></view>
                <view class="size32 color_33 bold">选择支付账户</view>
            </view>
            <view class="row m-top30">
                <view
                    class="item flexac f-column"
                    :class="{ active: payType == item.payType, disabled: item.money && parseFloat(item.money) < parseFloat(paymentMoney) }"
                    @click="changePay(item)"
                    v-for="(item, index) in payMode"
                    :key="index"
                >
                    <view class="size28">{{ item.title }}</view>
                    <view class="h6 color_99 m-top4" v-if="item.money">{{ item.money }}</view>
                </view>
            </view>
        </view>
        <view class="footer bgwhite">
            <view class="flex-1">
                <view class="h6 color_33" v-if="subscribe_date">{{ subscribe_date }}</view>
                <view class="thmeColor bold">
                    <text class="size28">￥</text>
                    <text class="size48">{{ paymentMoney }}</text>
                </view>
            </view>
            <view class="btn flexac size34 white" @click="Continue">立即预约</view>
        </view>

        <u-popup :show="showdetails" :round="10" closeable @close="showdetails = false">
            <view class="padding30">
                <view class="size36 color_33 bold m-bot30">服务详情</view>
                <view class="detailsPop">
                    <u-swiper height="600rpx" :list="swiperList" :autoplay="false" bgColor="#fff" indicator indicatorMode="line" @click="previewImg"></u-swiper>
                    <view class="size32 bold m-top30">{{ details.name }}</view>
                    <view class="m-top10 m-bot30">
                        <text class="size28 thmeColor bold">￥</text>
                        <text class="size40 thmeColor bold">{{ parseFloat(details.price) }}</text>
                        <text class="h6 color_B3 line-through m-left4" v-if="parseFloat(details.full_price) > parseFloat(details.price)">￥{{ parseFloat(details.full_price) }}</text>
                    </view>
                    <u-parse :content="details.content" :domain="imgUrl"></u-parse>
                </view>
            </view>
        </u-popup>

        <u-calendar
            ref="calendar"
            :show="showCalendar"
            :formatter="formatter.bind(this)"
            mode="single"
            :showTitle="false"
            :color="color"
            :customList="customList"
            :defaultDate="scanDate"
            closeOnClickOverlay
            @close="showCalendar = false"
            @confirm="confirm"
        ></u-calendar>

        <u-picker :show="showArrivalTime" :columns="[arrivalTimeList]" keyName="title" title="请选择预计送达时间" @cancel="showArrivalTime = false" @confirm="changeArrivalTime"></u-picker>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    import Api from '@/common/Api.js';
    import Coupon from './components/Coupon.vue';
    import Points from './components/Points.vue';
    export default {
        components: {
            Coupon,
            Points
        },
        data() {
            return {
                imgUrl: this.imgUrl,
                goods_id: '',
                scanDate: '', // 当前激活的日期
                current: 0,
                goods_num: 1,
                delivery: 2, // 自提
                dateList: [],
                customList: [],
                subscribe_date: '', // 用来提交
                select_date: '', // 用来打点
                showCalendar: false,
                utel: '',
                uname: '',
                remark: '',
                Sale: '',
                couponsId: '',
                useIntegral: 0, // 1使用积分
                showdetails: false,
                details: '',
                swiperList: [],
                pageData: '',
                payMode: [], // 支付方式
                payType: '',
                paymentMoney: '', // 实付款
                playid: '',
                payFlag: 0,
                order_id: '',
                arrivalTimeList: [],
                arrivalTime: '',
                times: '',
                showArrivalTime: false,
                tip: ''
            };
        },
        computed: {
            ...mapState(['color', 'share_v_id', 'openid']),
            requestData() {
                return {
                    specs: '',
                    goods_id: this.goods_id,
                    pageData: this.pageData,
                    goods_num: this.goods_num,
                    couponsId: this.couponsId,
                    useIntegral: this.useIntegral
                };
            }
        },
        onReady() {
            // 如果需要兼容微信小程序的话，需要用此写法
            this.$refs.calendar.setFormatter(this.formatter);
        },
        onLoad(e) {
            if (e.goods_id) this.goods_id = e.goods_id;
            if (e.scanDate) {
                this.scanDate = e.scanDate;
                this.getArrivalTime();
            }
            this.getPageData();
            this.getTimes();
            this.getOldAddress();
        },
        onUnload() {
            this.payFlag = 0;
        },
        onShow() {
            let options = wx.getEnterOptionsSync();
            if (options.scene == '1038' && options.referrerInfo.appId == 'wxef277996acc166c3' && this.payFlag == 1) {
                let extraData = options.referrerInfo.extraData;
                if (!extraData) return;
                if (extraData.code == 'success') {
                    this.$rectTo('/pages/index/pay_scs?playid=' + this.playid);
                } else {
                    this.$rectTo('/orderPage/order/reserveRecord?order_id=' + this.order_id);
                }
            }
        },
        methods: {
            getArrivalTime() {
                this.$http
                    .post({
                        url: '/zzj_singleSaleApi/getSystemArrivalTime',
                        data: {
                            scanDate: this.scanDate,
                            times: this.times
                        }
                    })
                    .then((res) => {
                        if (res.errcode != 100) return this.$Toast(res.msg);
                        this.arrivalTimeList = res.data || [];
                    });
            },
            changeArrivalTime(e) {
                console.log(e);
                this.arrivalTime = e.value[0].title;
                this.showArrivalTime = false;
            },
            formatter(day) {
                if (this.select_date) {
                    const d = this.select_date.split('-');
                    if (day.month == d[1] && day.day == d[2]) day.dot = true;
                }
                return day;
            },
            getPageData() {
                this.$http
                    .get({
                        url: '/zzj_singleSaleApi/getPurchase',
                        data: {
                            goods_id: this.goods_id,
                            num: this.goods_num,
                            delivery: this.delivery
                        }
                    })
                    .then((res) => {
                        if (res.code != 100) return this.$Toast(res.msg);
                        let result = res;
                        this.paymentMoney = result.totalMoney;
                        this.payMode = result.payMode || [];
                        if (this.payMode.length) {
                            let first = this.payMode.find((item) => !item.money || parseFloat(item.money) >= parseFloat(this.paymentMoney));
                            if (first) this.payType = first.payType;
                        }
                        this.pageData = result;
                        this.getPreferential();
                    });
            },
            getTimes() {
                this.$http
                    .post({
                        url: '/goodsSubscribeApi/getGoodsTimeAppointment',
                        data: {
                            goods_id: this.goods_id,
                            scanDate: this.scanDate
                        }
                    })
                    .then((res) => {
                        if (res.errcode != 100) return this.$Toast(res.msg);
                        if (res.tip) this.tip = res.tip;
                        this.dateList = res.data || [];
                        this.customList = this.dateList.map((item) => item.scanData);
                        if (!this.dateList.length) return;
                        let index = this.dateList.findIndex((item) => item.scanData == this.scanDate);
                        if (index > -1) this.current = index;
                    });
            },
            selectDate(item, index) {
                this.scanDate = item.scanData;
                this.current = index;
                this.arrivalTime = '';
                this.getArrivalTime();
            },
            selectTime(item, date) {
                if (item.num < 1) return;
                this.subscribe_date = item.subscribe_date;
                this.select_date = date;
                this.times = item.times;
                this.arrivalTime = '';
                this.getArrivalTime();
            },
            changeSwiper(e) {
                this.current = e.detail.current;
                this.scanDate = this.dateList[this.current].scanData;
            },
            confirm(e) {
                this.scanDate = e[0];
                let index = this.dateList.findIndex((item) => item.scanData == this.scanDate);
                if (index > -1) this.current = index;
                this.showCalendar = false;
            },
            opendetails(item) {
                this.details = item;
                // 轮播图
                let photo = [];
                if (item.photo) {
                    photo = item.photo.split(',');
                    this.swiperList = photo.map((item) => ({ url: this.$imgUrls(item), type: 'image' }));
                }
                if (item.video) this.swiperList.unshift({ url: item.video, type: 'video' });
                this.showdetails = true;
            },
            previewImg(index) {
                if (this.swiperList[index].type != 'image') return;
                let urls = [];
                this.swiperList.forEach((item) => {
                    if (item.type == 'image') {
                        urls.push(item.url);
                    }
                });
                uni.previewImage({
                    current: this.swiperList[index].url,
                    urls,
                    indicator: 'number'
                });
            },
            getOldAddress() {
                this.$http
                    .post({
                        url: '/SRA_simMallApi/getOldAddress',
                        data: {
                            type: 3
                        }
                    })
                    .then((res) => {
                        if (res.code != 100) return this.$Toast(res.msg);
                        let result = res.data || '';
                        this.uname = result.uName;
                        this.utel = result.uTel;
                    });
            },
            async getPreferential() {
                const paramData = await Api.getPreferential(this.requestData);
                this.Sale = paramData;
                this.paymentMoney = paramData.payMoney;
            },
            Use_couponId(event) {
                this.couponsId = event;
                this.getPreferential();
            },
            Use_points() {
                this.useIntegral = this.useIntegral == 1 ? 0 : 1;
                this.getPreferential();
            },
            changePay(item) {
                if (item.money && parseFloat(item.money) < parseFloat(this.paymentMoney)) return;
                this.payType = item.payType;
            },
            Continue() {
                if (this.playid) return this.pay_money(this.playid);
                if (this.pageData.allowBuy == 0) return this.$Toast(this.pageData.allowBuyTitle);
                if (!this.subscribe_date) return this.$Toast('请选择预约时间');
                if (!this.utel) return this.$Toast('手机号码不能为空');
                if (!this.$reg.phone.test(this.utel)) return this.$Toast('手机号码不正确');
                if (!this.uname) return this.$Toast('姓名不能为空');
                if (this.arrivalTimeList.length && !this.arrivalTime) return (this.showArrivalTime = true);
                if (this.tip) {
                    this.$Modals('提示', this.tip, '取消', '确定支付').then((config) => {
                        if (config) this.InitiatePayment();
                    });
                } else {
                    this.$Modal('是否确定支付', '支付成功后可在我的订单中查看').then((config) => {
                        if (config) this.InitiatePayment();
                    });
                }
            },
            InitiatePayment() {
                let url;
                let params = {
                    delivery: this.delivery,
                    uname: this.uname,
                    utel: this.utel,
                    express: this.pageData.express,
                    totalMoney: this.paymentMoney,
                    remarks: this.remark,
                    couponID: this.couponsId,
                    useIntegral: this.useIntegral,
                    share_v_id: this.share_v_id,
                    aes_coupon: this.Sale.aes_coupon || '',
                    subscribe_date: this.subscribe_date
                };
                if (this.goods_id) {
                    url = '/zzj_singleSaleApi/generateOrder';
                    params.goods_id = this.goods_id;
                    params.num = this.goods_num;
                    params.single = 1;
                }
                if (this.arrivalTime) {
                    let arrivalText = '预计到达时间：' + this.arrivalTime;
                    params.remarks = params.remarks ? `${params.remarks}|${arrivalText}` : arrivalText;
                }

                this.$showLoading('');
                this.$http
                    .post({
                        url,
                        data: params
                    })
                    .then((res) => {
                        this.$hideLoading();
                        if (res.code != 100) return this.$Toast(res.msg);
                        // #ifdef H5
                        window.location.href = 'https://sra.mogoie.com/index.php/accountPay/weChatCashierPage?orderStr=' + res.payID;
                        // #endif

                        // #ifndef H5
                        this.playid = res.payID;
                        this.pay_money(res.payID);
                        // #endif

                        this.order_id = res.id;
                    });
            },
            pay_money(playid) {
                let that = this;
                this.$showLoading('支付中···');
                this.$http
                    .post({
                        url: '/accountPay/cashierStorePageAjax',
                        data: {
                            orderAesStr: playid,
                            payType: this.payType,
                            openId: this.openid
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();
                        if (res.code != 100) return this.$Toast(res.msg);
                        let Result = res.data;
                        if (this.payType == 1) {
                            // 微信支付
                            // #ifdef MP-WEIXIN
                            if (Result.extraData) {
                                this.payFlag = 1;
                                wx.openEmbeddedMiniProgram({
                                    appId: Result.appId,
                                    extraData: Result.extraData
                                });
                            } else {
                                uni.getProvider({
                                    service: 'oauth',
                                    success: function (resp) {
                                        if (resp.provider) {
                                            uni.requestPayment({
                                                provider: resp.provider[0],
                                                orderInfo: Result,
                                                timeStamp: Result.timeStamp,
                                                nonceStr: Result.nonceStr,
                                                package: Result.package,
                                                signType: Result.signType,
                                                paySign: Result.paySign,
                                                success: function () {
                                                    that.$rectTo('/pages/index/pay_scs?playid=' + playid);
                                                },
                                                fail: function (err) {
                                                    console.log('fail:' + JSON.stringify(err));
                                                    that.$rectTo('/orderPage/order/reserveRecord?order_id=' + that.order_id);
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                            // #endif
                        } else {
                            this.$rectTo('/pages/index/pay_scs?playid=' + playid);
                        }
                    });
            }
        }
    };
</script>

<style lang="scss" scoped>
    .page {
        background-color: #f7f7f7;
        padding-bottom: calc(146rpx + constant(safe-area-inset-bottom));
        padding-bottom: calc(146rpx + env(safe-area-inset-bottom));
    }
    .goods_item {
        height: 200rpx;
        display: flex;
        align-items: center;
        padding: 0 150rpx 0 30rpx;
        .img {
            width: 170rpx;
            height: 150rpx;
            border: 2rpx solid #f3f3f3;
            border-radius: 10rpx;
        }
        .btn {
            width: 140rpx;
            height: 40rpx;
            background: #f2f2f2;
            border-radius: 20rpx 0 0 20rpx;
            right: 0;
            top: 24rpx;
        }
    }
    .detailsPop {
        height: 70vh;
        overflow-y: auto;
    }
    .divider {
        width: 6rpx;
        height: 28rpx;
        background: var(--color);
        margin-right: 8rpx;
    }
    .date {
        display: inline-block;
        text-align: center;
        padding: 10rpx 12rpx;
        border-radius: 10rpx;
        &.selected {
            position: relative;
            &::after {
                content: '';
                width: 12rpx;
                height: 12rpx;
                background: var(--color);
                border-radius: 50%;
                position: absolute;
                right: 0;
                top: 4px;
            }
        }
    }
    .calendar {
        width: 108rpx;
        padding: 10rpx 0;
        text-align: center;
        box-shadow: -4px 0px 4px rgba(0, 0, 0, 0.06);
        right: -30rpx;
        top: 0;
        z-index: 1;
    }
    .swiper {
        height: 148rpx;
    }
    .time {
        display: inline-block;
        width: 220rpx;
        border: 2rpx solid #f2f2f2;
        border-radius: 10rpx;
        overflow: hidden;
        margin-right: 20rpx;
        color: #515151;
        .top {
            height: 104rpx;
        }
        .bottom {
            height: 40rpx;
            background: #f5f5f5;
        }
        &.disabled {
            color: #b3b3b3;
            .top {
                background: #eee;
            }
            .bottom {
                background: #e1e1e1;
            }
        }
        &.active {
            border: 2rpx solid var(--color);
            .top,
            .bottom {
                color: var(--color);
            }
        }
    }
    .label {
        width: 190rpx;
    }
    .payList {
        background-color: #ffffff;
        padding: 30rpx 30rpx 0 0;
        .item {
            min-width: 204rpx;
            height: 120rpx;
            margin: 0 0 30rpx 30rpx;
            border: 1rpx solid #ccc;
            border-radius: 8rpx;
            &.active {
                border: 1rpx solid var(--color);
                > view {
                    color: var(--color);
                }
            }
            &.disabled {
                background: #f8f8f8;
                > view {
                    color: #ccc;
                }
            }
        }
    }
    .footer {
        width: calc(100% - 60rpx);
        height: 120rpx;
        border-top: 2rpx solid #ebebeb;
        position: fixed;
        left: 0;
        bottom: 0;
        z-index: 1;
        padding: 0 30rpx;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        box-sizing: content-box;
        display: flex;
        align-items: center;
        .btn {
            width: 260rpx;
            height: 90rpx;
            background: var(--color);
            border-radius: 90rpx;
        }
    }
</style>
